<template>
  <a-button type="primary" class="upload-btn">
    上传文件
    <input type="file" @change="uploadVideoFun" />
  </a-button>
  <p>视频路径：{{ videoSrc }}</p>
  <a-button type="primary" class="upload-btn" @click="start">
    开始播放
  </a-button>

  <video id="videoElement" ref="videoElement" controls autoplay class="video-js"></video>
</template>

<script setup>
import Hls from "hls.js";
import { ref, onMounted } from "vue";
import { UploadVideo } from "@/api/video";
import { message } from "ant-design-vue";

const videoElement = ref();

var videoSrc = ref("video-temp/87ab8366-b638-44e0-a47a-86d929fc346d/video.m3u8"); // 用于获取m3u8文件的地址, 后端处理跨域

function playVideo() {
  videoElement.value.play();
}

function pauseVideo() {
  videoElement.value.pause();
}

function loadVideo() {
  if (Hls.isSupported()) {
    // 组件挂载完成, 才能获取到video元素
    var video = document.getElementById("videoElement");
    // 可参考:
    // hls的github文档中的api：(https://github.com/video-dev/hls.js/blob/master/docs/API.md)
    // hls.js如何播放m3u8文件（实例）？(https://blog.csdn.net/ffffffff8/article/details/129314268)
    // Vue 之 视频流 - Hls.js(https://blog.csdn.net/a15297701931/article/details/115478652)
    let config = {
      xhrSetup: function (xhr, url) {
        xhr.withCredentials = true; // 会携带cookie
        xhr.setRequestHeader(
          "Authorization",
          `Bearer ${sessionStorage.getItem("token")}`
        ); // 设置请求头
      },
    };
    var hls = new Hls(config);

    hls.on(Hls.Events.MEDIA_ATTACHED, function () {
      console.log("video和hls.js现在绑定在一起了!");
    });

    hls.on(Hls.Events.MANIFEST_PARSED, function (event, data) {
      console.log(
        "manifest loaded, found " + data.levels.length + " quality level"
      );
      // video.play() // 不能在这里就播放, 需要用于与dom元素有交互才可以播放, 否则浏览器会报错
    });
    let url = [
      videoSrc.value,
    ].join("");
    console.log(url);
    hls.loadSource(
      // "http://playertest.longtailvideo.com/adaptive/bipbop/gear4/prog_index.m3u8"
      url
    );
    // bind them together
    hls.attachMedia(video);
  } else {
  }
}
const uploadVideoFun = async (e) => {
  console.log(e.target.files[0]);
  if (e.target.files[0]) {
    let formData = new FormData();
    formData.append("video", e.target.files[0]);
    const { msg, success, data } = await UploadVideo(formData);
    console.log(data);
    if (success) {
      videoSrc.value = data;
      message.success(msg);
    } else {
      message.error(msg);
    }
  }
};

const start = () => {
  loadVideo();
};

onMounted(() => { });
</script>
<style lang="scss" scoped>
.video-js {
  width: 100%;
}

.upload-btn {
  position: relative;

  input {
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    position: absolute;
    opacity: 0;
  }
}
</style>